package cn.yotta.user.web.autoconfiguration.filter;

import cn.yotta.common.api.model.Response;
import cn.yotta.user.web.autoconfiguration.context.tenant.TenantContext;
import cn.yotta.user.web.autoconfiguration.provider.TenantResolveProvider;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wyaoyao
 * @date 2022/11/8 17:01
 */
public class TenantContextFilter implements Filter {

    private final TenantResolveProvider tenantLoadProvider;
    /**
     * 过滤器顺序，数字越小，越先执行, 放到UserContextFilter之后运行
     */
    public final static Integer ORDER = -9998;


    private final ObjectMapper objectMapper = new ObjectMapper();


    public TenantContextFilter(TenantResolveProvider tenantLoadProvider) {
        this.tenantLoadProvider = tenantLoadProvider;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        try {
            final Long tenantId = tenantLoadProvider.loadTenantId(httpServletRequest);
            TenantContext.setTenantId(tenantId);
            chain.doFilter(servletRequest, servletResponse);
        } catch (TenantResolveProvider.TenantNotResolveException e) {
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(Response.fail("无法解析租户ID，请联系系统管理员", HttpServletResponse.SC_UNAUTHORIZED)));
            return;
        } finally {
            TenantContext.clear();
        }
    }
}
